const appUser = getApp();
const db = wx.cloud.database();
const _ = db.command;
var id = null;
Page({
  // 页面的初始数据
  data: {

    name: "",
    phone: "",
    provinceName: "", //省
    cityName: "", //市
    districtName: "", //区·
    address: "", //详细地址
    checked: false,
    okButton: "新增地址"
  },

  bindRegionChange(e) {
    console.log(e.detail.value[0])
    this.setData({
      provinceName: e.detail.value[0],
      cityName: e.detail.value[1],
      districtName: e.detail.value[2]
    })
  },
  onChange() {
    this.setData({
      checked: !this.data.checked
    })
  },
  // 保存收货地址
  save() {

    if (this.data.name == "") {
      wx.showToast({
        icon: 'error',
        title: '请输入名字'
      })
    } else if (this.data.phone.length != 11) {
      console.log(this.data.phone.length)
      wx.showToast({
        icon: 'error',
        title: '请输入手机号'
      })
    } else if (this.data.provinceName == "" || this.data.cityName == "" || this.data.districtName == "") {
      wx.showToast({
        icon: 'error',
        title: '请输入所在地区'
      })
    } else if (this.data.address == "") {
      wx.showToast({
        icon: 'error',
        title: '请输入详细地址'
      })
    } else {
      var obj = {
        "name": this.data.name,
        "phone": this.data.phone,
        "address": this.data.provinceName + this.data.cityName + this.data.districtName + this.data.address
      }

      if (this.data.okButton == "修改地址") {
        db.collection("user2").where({
          _openid: appUser.globalData.userOpenid
        }).update({
          data: {
            ['address.' + id]: obj,
          }
        })
        wx.showToast({
          icon: 'success',
          title: '修改成功',
          duration: 1000
        })
        setTimeout(() => {
          wx.navigateBack({
            delta: 1,
          })
        }, 1000);
      } else if (this.data.okButton == "新增地址") {
        db.collection("user2").where({
          _openid: appUser.globalData.userOpenid
        }).update({
          data: {
            address: _.push(obj)
          }
        })
        wx.showToast({
          icon: 'success',
          title: '新增地址成功',
          duration: 1000
        })
        setTimeout(() => {
          wx.navigateBack({
            delta: 1,
          })
        }, 1000);
      }
    }
  },
  onLoad: function (options) {

    if (options.id) {
      id = (Number)(options.id)
      console.log(id)
      db.collection("user2").where({
        _openid: appUser.globalData.userOpenid
      }).get({
        success: res => {
          console.log(res)
          res = res.data[0].address[id]
          this.setData({
            name: res.name,
            phone: res.phone,
            okButton: "修改地址"
          })
        }
      })
    }

    if (options.id) {
      wx.setNavigationBarTitle({
        title: '修改收获地址'
      })
    }

  },

  // 省市区选择
  onAddressChange(event) {}
})